<?php
/*
 * user center base class
 * uther 2012.8.17 start
 */

class Union{
	
	var $db = '';
	function __construct(){
		$ci = &get_instance();
		$this->db = $ci->db;
		session_start();
	}
	
	function clearLogin(){
		$this->set_cookie();
	}
	
	function autoLogin($ret_user = array()){
		$login_back_url ='http://www.geili0574.com/index.php/tbk';
		$_SESSION['uid']   = $ret_user['user_id'];
	    $_SESSION['usermail'] = $ret_user['user_name'];
        $_SESSION['login_from'] = $ret_user['come_from'];
        $_SESSION['email'] = $ret_user['email'];
		$this->page_redirect($login_back_url, true);
	}
	
	
	function page_redirect($url = '', $is_login_ok = false){
		if (!$is_login_ok){
			if (isset($_SESSION['union_login_from'])){
				$login_from = $_SESSION['union_login_from'];
				unset($_SESSION['union_login_from']);
			}
			
			if (isset($_SESSION['login_back_url'])){
				$login_back_url = trim($_SESSION['login_back_url']);
				unset($_SESSION['login_back_url']);
			}
			else{
				$login_back_url = '';
			}
			$url = empty($url) ? (empty($login_back_url) ? '' : $login_back_url) : $url;
		
		}
		header("Location: ". $url ."\n");exit;
	}
	
	function build_request_str($params = array(), $is_urlencode = false, $is_filter = false){
		$api_str = '';
	    foreach ($params as $key => $value){
	    	if($is_filter){
	    		if(empty($value) || $key == 'sign' || $key == 'sign_type')continue;
	    	}
	    	else
	    		if(empty($value))continue;
	    	
	        $api_str .= $key . '=' . ($is_urlencode ? urlencode($value) : $value) .'&';
	    }
	    $api_str = substr($api_str, 0, -1);

    	return $api_str;
	}
	
	function khash($data) {
	    static $map="abcdefghijk2345qrstuvwxyz67KLMNOPQRSTU89lmnopABCDEFGHIJVWXYZ";
	    $hash=crc32($data)+0x100000000;
	    $str = "";
	    do {
	        $str = $map[31+ ($hash % 31)] . $str;
	        $hash /= 31;
	    } while($hash >= 1);     
	    return $str;
	}
	
	function get_rand_passwd($openid = ''){
		return strtolower(substr(md5($openid), 4, 8));
	}
	
	function check_exists_openid($openid = '', $from = ''){
		/* 检测数据库中是否存在openid */
		$res = $this->db->get_where('tb_union_users', array('openid' => $openid,'come_from'=>$from));
		if($res->num_rows>0){
			$res = $res->result();
			$row['is_bind'] = $res[0]->is_bind;
			$row['core_id'] = $res[0]->core_id;
			$row['user_id'] = $res[0]->user_id;
			$row['user_name'] = $res[0]->user_name;
			$row['email'] = $res[0]->email;
			$row['union_id'] = $res[0]->union_id;
			$row['add_time'] = $res[0]->add_time;
			$row['come_from'] = $res[0]->come_from;
			$row['openid'] = $res[0]->openid;
			$row['token'] = $res[0]->token;
			return $row;
		}else{
			return false;
		}
	}
	
	function refresh_user_token($union_id = 0, $token = '', $expire = 0, $refresh_time = false){

		$time =time();
		$sql = "UPDATE `tb_union_users` SET token='$token',last_update = '$time', expire ='$expire' WHERE union_id = '$union_id'";
		$this->db->query($sql);
		
		return true;
	}
	
	function get_rand_name(){
		$str = uniqid('', true);
		list($tmp, $username) = explode('.', $str);
		return $username;
	}
	

	function check_exists_name($username = '', $from = ''){
		$is_exists = 1;
		$keywords = '_' . $from;
		
		/* 检测账号是否合法 */
		$username = preg_replace('/[:\'\/%,\\*\\"\\s\\t\\<\\>\\&\'\\\\]/', '', $username);

		if(empty($username) || mb_strlen($username, 'UTF-8')<2)$username = get_rand_name();
		
		$oriname = $username;
		
		while($is_exists){
			$sql = "SELECT count(id) AS c FROM `os_user` WHERE usermail = ?";
			$res = $this->db->query($sql,$username);
			$res = $res->result();
			$num = $res[0]->c;
			
			$is_exists = $num;
			
			if($is_exists){
				$rnd = rand(1, 9) . str_pad(mt_rand(0, 999), 3, '0', STR_PAD_LEFT);
				$username = $oriname . '_' . str_replace('4', '8', $rnd);
			}
			
		}
		return $username;
	}
	
	function add_union_account($user = array()){
		$user['user_name'] = strip_tags($user['user_name']);
		$user['user_name'] = empty($user['user_name']) ? 'by_'.$this->get_rand_name() : $user['user_name'];
		
		$this->db->insert('tb_union_users', $user); 
		$union_id = $this->db->insert_id();
		
		$tmpid = 'uid_' . $union_id;
		/* 插入到user表 */
		$rand_passwd = $this->get_rand_passwd($user['openid']);
		$reg_user = array(
								'usermail' => $tmpid,
								'password' => md5($rand_passwd),
								'fanli' =>'0.00',
								'is_fanli' =>'0.00'
						);

		$this->db->insert('tb_user', $reg_user); 
		$user_id = $this->db->insert_id();

		/* 更新 union_users表 */
		
		$data['user_id'] = $user_id;
		$data['tmpid'] = $tmpid;
		$this->db->where('union_id', $union_id);
		$this->db->update('tb_union_users', $data); 
		unset($data);

		$ret_user = array();
		$ret_user['is_bind'] = 0;
		$ret_user['core_id'] = 0;
		$ret_user['user_id'] = $user_id;
		$ret_user['user_name'] = $user['user_name'];
		$ret_user['email'] = $reg_user['email'];
		$ret_user['come_from'] = $user['come_from'];
		$ret_user['openid'] = $user['openid'];
		$ret_user['token'] = isset($user['token']) ? $user['token'] : '';
		return $ret_user;
	}
	
	function switch_user($union_id = 0, $core_id = 0, $to_core_id = FALSE){
		if ($union_id == 0 || $core_id == 0)return false;
		
		if ($to_core_id){
			$sql = "SELECT user_id, user_name, email FROM `os_users` WHERE user_id = '$core_id' limit 1";
		}
		else
			$sql = "SELECT user_id, user_name, email FROM `os_union_users` WHERE union_id = '$union_id' AND core_id = '$user_id' AND is_bind = 1 limit 1";
		
		$res = $this->db->query($sql);
		if($res->num_rows()>0){
			$res = $res->result();
			$row['user_id'] = $res[0]->user_id;
			$row['user_name'] = $res[0]->user_name;
			$row['email'] = $res[0]->email;
		}
		else{
			$row = false;
		}
		if($row){
			$this->set_cookie();
			$_SESSION['user_id']   = $row['user_id'];
            $_SESSION['user_name'] = $row['user_name'];
            $_SESSION['email']     = $row['email'];
	        
	        return true;
		}
		return false;
	}

	function set_cookie($username='', $remember= null )
    {
    	$this->cookie_path='/';
    	$this->cookie_domain='.geili0574.com';
        if (empty($username))
        {
            /* 摧毁cookie */
            $time = time() - 3600;
            setcookie("tb[uid]",  '', $time, $this->cookie_path);            
            setcookie("tb[password]", '', $time, $this->cookie_path);

        }
        elseif ($remember)
        {
            /* 设置cookie */
            $time = time() + 3600 * 24 * 15;

            setcookie("tb[usermail]", $username, $time, $this->cookie_path, $this->cookie_domain);
            
            $sql = "SELECT id, password FROM `os_user` WHERE usermail='$username' LIMIT 1";
            $res = $this->db->query($sql);
            $res = $res->result();
            if ($res)
            {
            	$row['id'] = $res[0]->user_id;
            	$row['password'] = $res[0]->password;
                setcookie("tb[uid]", $row['id'], $time, $this->cookie_path, $this->cookie_domain);
                setcookie("tb[password]", $row['password'], $time, $this->cookie_path, $this->cookie_domain);
            }
        }
    }
}
/*
 * uther user center base class
 * end
 */
?>